//用户相关小仓库
import { defineStore } from "pinia";
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";

import type { UserState } from "@/store/modules/types/type";
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from "@/utils/token";
import { constantRoute } from "@/router/routes";
import type { loginFormData, loginResponseData } from "@/api/user/type";

//创建用户小仓库
const useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: ''
    };
  },
  actions: {
    async userLogin(data: loginFormData) {
      const res: loginResponseData = await reqLogin(data);
      if (res.code === 200) {
        this.token = res.data as string;
        SET_TOKEN(res.data as string);
        return "ok";//登录成功
      } else {
        return Promise.reject(new Error(res.message || "登录失败"));//登录失败
      }
    },
    async userInfo(){
      //获取用户信息，并存储到仓库
      //@ts-ignore
      const res: userInfoResponseData = await reqUserInfo()
        if(res.code === 200) {
          this.username = res.data.name
          this.avatar = res.data.avatar
          return 'ok'//获取用户信息成功
        }else{
          return Promise.reject(new Error(res.message || "获取用户信息失败"))//获取用户信息失败
        }
    },
    async userLogout(){
      let result:any = await reqLogout()
      if(result.code === 200){
        this.token = null
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'//退出登录成功
      }else{
        return Promise.reject(new Error(result.message || "退出登录失败"))//退出登录失败
      } 
    }
  },
  getters: {},
});

export default useUserStore;
